package com.travel.server.manager.impl.command.article;

import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.article.QueryArticleListRequest;
import com.travel.server.manager.dto.response.article.QueryArticleListResponse;
import com.travel.server.manager.dto.response.article.QueryArticleListResponse.ArticleItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.ArticleClassDal;
import com.travel.server.manager.impl.dal.ArticleDal;
import com.travel.server.manager.impl.dal.PageDto;
import com.travel.server.manager.model.ArticleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/20 16:00
 * @Desc:
 */
@Component
public class QueryArticleListCommand extends AbstractCommand<QueryArticleListRequest, QueryArticleListResponse> {

    @Autowired
    private ArticleDal articleDal;

    @Autowired
    private ArticleClassDal articleClassDal;

    @Override
    protected void checkInput(QueryArticleListRequest request) {
        checkPageInput(request);
    }

    @Override
    public QueryArticleListResponse handle(QueryArticleListRequest request) {
        checkInput(request);

        QueryArticleListResponse response = new QueryArticleListResponse();
        List<ArticleItem> articleList = new ArrayList<>();
        PageDto<ArticleInfo> pageDto = articleDal.selectByPage(request.getOffset(), request.getLimit());
        List<ArticleInfo> list = pageDto.getList();
        response.setTotalNum(pageDto.getTotal());
        if(CollectionUtil.isEmpty(list)){
            response.setArticleList(articleList);
            return response;
        }

        List<Integer> classIdList = new ArrayList<>();
        for(ArticleInfo info : list){
            classIdList.add(info.getClassId());
        }

        Map<Integer, String> classMap = articleClassDal.makeMap(classIdList);
        for(ArticleInfo info : list){
            ArticleItem item = new ArticleItem();
            item.setClassId(info.getClassId());
            item.setClassName(classMap.get(info.getClassId()));
            item.setCreateDate(info.getCreateTime());
            item.setId(info.getId());
            item.setIsPublish(info.getIsPublish());
            item.setTitle(info.getArticleTitle());
            articleList.add(item);
        }
        response.setArticleList(articleList);

        return response;
    }
}
